<template>
  <div class="msg">
    <MsgNav :select-mode="selectMode" @switch="handleSwitch">
      <van-tabs shrink v-model:active="activeTab" class="msg-tabs" @change="handleTabChange">
        <van-tab :title="titleInBox" name="in-box" />
        <van-tab :title="titleOutbox" name="outbox" />
      </van-tabs>
    </MsgNav>
    <div ref="refList" class="content-list">
      <MsgList
        :active-tab="activeTab"
        :select-mode="selectMode"
        @switch="handleSwitch"
        @refresh="initMessageList"
      />
    </div>
    <Tabbar v-if="!selectMode" />
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, onActivated } from 'vue'
import { storeToRefs } from 'pinia'
import { useMsgStore } from '@/store'
import { onBeforeRouteLeave } from 'vue-router'
import Tabbar from '@/components/Tabbar'
import MsgNav from './components/MsgNav.vue'
import MsgList from './components/MsgList.vue'

// 多选模式切换
const selectMode = ref<boolean>(false)
const handleSwitch = (value: boolean) => {
  selectMode.value = value
}

// 切换标签页时列表滚动到顶部
const refList = ref<HTMLElement | null>(null)
const activeTab = ref<string>('in-box')
const handleTabChange = () => {
  if (refList.value) {
    refList.value.scrollTop = 0
  }
}

// 获取消息列表
const msgStore = useMsgStore()
const initMessageList = () => {
  msgStore.fetchMessageList()
}

// 根据消息条数生成标题
const { receiveList, sendList } = storeToRefs(msgStore)
const titleInBox = computed(() => {
  // if (activeTab.value === 'in-box') {
  return `收件箱(${receiveList.value.length})`
  // }
  // return '收件箱'
})
const titleOutbox = computed(() => {
  // if (activeTab.value === 'outbox') {
  return `发件箱(${sendList.value.length})`
  // }
  // return '发件箱'
})

// 页面keep-alive缓存时滚动条位置处理、数据刷新处理
let scrollTop: number = 0
onBeforeRouteLeave(() => {
  if (refList.value) {
    scrollTop = refList.value.scrollTop || 0
  }
})
onActivated(() => {
  initMessageList()
  if (refList.value) {
    refList.value.scrollTop = scrollTop
  }
})
</script>

<style lang="less" scoped>
.msg {
  height: 100vh;
  background-color: #fff;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  flex-direction: column;
  .msg-tabs {
    border-radius: 19.23px 19.23px 0px 0px;
    overflow: hidden;

    :deep(.van-tab__text) {
      font-size: 12.18px;
    }
  }

  .content-list {
    flex-grow: 1;
    overflow-y: scroll;
  }
}
</style>
